from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib.auth.models import User
from common.views.utils import table_api
from django.core.paginator import Paginator
from django.db.models import Q
from ..models import File

class FileListApiView(View):
    @method_decorator(login_required)
    def get(self,request):
        filters = []
        page = request.GET.get('page')
        limit = request.GET.get('limit')
        fileName = request.GET.get('fileName')
        if fileName:
            filters.append(Q(name__contains=fileName))
        files = Paginator(File.objects.filter(*filters).order_by('-ca_time'), limit).get_page(page)
        result = [{
            'id': item.id,
            'name': item.name,
            'path': item.path,
            'size': item.size,
            'type': item.type,
            'ca_by': FileListApiView.get_username(item.ca_by),
            'ca_time': item.ca_time,
            'up_time': item.up_time
        } for item in files]
        return table_api(result=result,total=files.paginator.count)

    @staticmethod
    def get_username(user_id):
        user = User.objects.get(id=user_id)
        return user.username